<?php

/*
 * C商城作功能模块
 * 功能：商城
 */

namespace User\Controller;

use Think\C_Controller;

class ShopController extends C_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->store_id = (int) $_GET['store_id'];
        if ($this->store_id < 1) {
            //throw new \Exception();
            $this->shoplist();
        }
        $s = new \Home\Logic\StoreLogic();
        $store = $s->getStore($this->store_id);
        $this->stores = $s->getBlocByStoreId($this->store_id);
        $this->assign('stores',$this->stores);
        $this->assign('logo', $store['logo']);
        $this->assign('store_name', $store['name']);
        $this->assign('store',$store);
        $this->item = new \Home\Logic\ShopitemLogic();
    }
    
    public function index(){
        layout('layout2');
        $items = $this->item->getItemsByStoreId($this->store_id,$status=1,true);
        foreach($items as $k=>$v){
            if($v['is_meal_set']==1){
                $meal_set_items = $this->item->getItemByMealSetId($v['id'], $this->store_id,true);
                $items[$k]['meal_set_items'] = $meal_set_items;   
            }
        }
        $this->assign('items',$items);
        $this->display('shop');
    }
    
    /*加入购物车*/
    public function addin(){
        
        $session_id = $_GET['session_id'];
        $item_id = (int)$_GET['item_id'];
        $store_id = (int)$_GET['store_id'];
        $re = $this->item->cartAddin($session_id,$item_id,$store_id);
        if($re==1){
            echo $re;  
        }else{
            echo false;
        }
    }
    
    /*从购物车删除*/
    public function delfrom(){
            $session_id = $_GET['session_id'];
            $item_number = $_GET['item_number'];
            $store_id = (int)$_GET['store_id'];
            $re = $this->item->cartDelfrom($session_id,$item_number,$store_id);
            echo $re;     
    }
    
    /*购物车*/
    public function shoppingcart(){
        /*if($_SESSION['client_id']<1){
            redirect("/user/passport/login?store_id=".$this->store_id);
        }*/
        
        layout('layout2');
        $_SESSION['s_verify'] = time();
        $this->setSession($_SESSION);
        $session_id = $_GET['session_id'];
        $store_id = (int)$_GET['store_id'];
        if($this->m->get($session_id)){
            $cart = $this->m->get($session_id);
            if(count($cart['carts'])<1){
                $this->assign('carts','false');
            }else{
                $carts = array();
                foreach ($cart['carts'] as $k => $v) {
			if($v==''){
                        continue;
                    }
                    $carts[] = $this->item->getItemByNumber($v,$store_id);
                    $this->assign('carts',$carts);
                } 
            }
        }else{
            $this->assign('carts','false');
        }

        $items = $this->item->getItemsByStoreId($this->store_id,$status=1,true);
        foreach($items as $k=>$v){
            if($v['is_meal_set']==1){
                $meal_set_items = $this->item->getItemByMealSetId($v['id'], $this->store_id);
                $items[$k]['meal_set_items'] = $meal_set_items;   
            }
        }
        $this->assign('items',$items);
        $this->display('cart');
    }
    
    /*商品详情页*/
    public function info(){
        layout(false);
        $item_number = trim($_GET['item_number']);
        $item_id = (int)$_GET['item_id'];
        if($item_id>0){
            $item = $this->item->getItemById($item_id,$this->store_id);
        }else{
            $item = $this->item->getItemByNumber($item_number,$this->store_id);
        }
        if($item['is_meal_set'] == 1){
            $items = $this->item->getItemByMealSetId($item['id'],$this->store_id,true);
            $old_price = 0;
            foreach($items as $v){
                $old_price += $v['price']*$v['number'];
            }
            $item['items'] = $items;
            $item['old_price'] = $old_price;
        }
        //微信分享
        $api = import('Api2', 'Weixin');
        $api = new \Weixin\Api2();
        $data['jsapi_ticket'] = $api->getTicket(WEIXIN_PAY_APP_ID, WEIXIN_PAY_SECRET);
        $data['noncestr'] = 'fewgasfgadussfeko'; //临时写死
        $data['timestamp'] = time();
        $data['url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ksort( $data );
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $data['sign'] = sha1(substr($str, 0, -1));
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $this->assign('weixin', true);
        }
        //评价
        $e = new \Home\Logic\EvaluateLogic();
        $evaluate = $e->getEvaluate($item['item_number'],$this->store_id);
        $score = $e->score($item['item_number'],$this->store_id);
        foreach($score as $k=>$v){
            if($v['star_level']=='0'){
                unset($score[$k]);
            }
            $arr = json_decode($v['star_level'],true);
            $sc += ($arr['total']+$arr['environment']+$arr['barber'])/3;
        }
        $score = substr($sc/(count($score)),0,3);
        $this->assign('score',$score);
        $this->assign('evaluate',$evaluate);

        $this->assign('data',$data);
        $this->assign('item',$item);
        $this->display('info');
    }

    public function mobile(){
        
        $mobile = trim($_GET['mobile']);
        $code = trim($_GET['code']);
        $data['mobile'] = $mobile;
        $data['store_id'] = (int)$_GET['store_id'];
        $data['item_id'] = $_GET['item_id'];
        $data['price'] = $_GET['price'];
        $data['num'] = $_GET['num'];
        $data['rmb'] = $_GET['rmb'];
        import('MsgCode','Msgcode');
        $m = new \Msgcode\MsgCode();
        if(!$m->checkCode($mobile, $code)){
            redirect(shop_buildUrl('/user/shop/shoppingcart?msg=1'));
        }
        $u = new \Home\Logic\UserLogic();
        $user = $u->getUserByAccount($mobile);
        if($user ==''){
            $re = $u->createUser($mobile);
            $data['client_id'] = $re;
        }else{
            $data['client_id'] = $user['id'];
        }
        $_SESSION['client_id'] = $data['client_id'];
        $this->setSession($_SESSION);
        if($data['client_id']>1){
            foreach($data['item_id'] as $v){
                $_item = $this->item->getItemById($v,$data['store_id']);
                if($_item['status']!=1){
                    $this->display('fales');exit;
                }
            }
            $order_number = $this->cartCreateOrder($data);
            if($order_number){
                $this->getOrderInfo($order_number);
            } 
        }
    }


    public function cartCreateOrder($data){
        $order = new \Home\Logic\OrderLogic();
        foreach($data['item_id'] as $k=>$v){
            if($v==''){
                continue;
            }
            $item= $this->buildOrderInfo($v,$data['store_id'],$data['num'][$k]);
            $order_info[] = $item;
            
        }
        $array['mobile'] = $data['mobile'];
        $array['store_id'] = $data['store_id'];
        $array['client_id'] = $data['client_id'];
        $array['rmb'] = $data['rmb'];
        $array['type'] = implode(',',$data['item_id']);
        $re = $order->cartCreateOrder($array,$order_info);
        if($re===false){
            $this->display('false');
        }

        return $re;
        
    }


    private function buildOrderInfo($item_id,$store_id,$num){
        $_item = $this->item->getItemById($item_id, $store_id,true);
        $session_id = session_id();
        if($_item['is_meal_set'] == 1){ //如果为套餐商品，则有多条子订单
            $_items = $this->item->getItemByMealSetId($_item['id'], $store_id,true);
            foreach($_items as $k=>$v){
                $info[$k]['store_id'] = $store_id;
                $info[$k]['item_id'] = $v['id'];
                $info[$k]['item_number'] = $v['item_number'];
                $info[$k]['number'] = $v['number']*$num;
                $info[$k]['count'] = $v['number']*$num;
                $this->item->cartDelfrom($session_id,$info[$k]['item_number'],$info[$k]['store_id']);
            }
        }else{ //单品
            $info[0]['store_id'] = $store_id;
            $info[0]['item_id'] = $_item['id'];
            $info[0]['item_number'] = $_item['item_number'];
            $info[0]['number'] = $num;
            $info[0]['count'] = $num;        //单品数量固定为1
            $this->item->cartDelfrom($session_id,$info[0]['item_number'],$info[0]['store_id']);
        }

        return $info;
    }

    public function getOrderInfo($order_number){
        $order = new \Home\Logic\OrderLogic();
        $order_info = new \Home\Logic\OrderinfoLogic();
        $data = $order->getOrder($order_number);
        $info_data = $order_info->getOrderInfo($data['id'],$data['store_id']);
        $this->assign('data',$data);
        $this->assign('info_data',$info_data);
        $this->display('settlement');
    }

    //支付
    public function pay(){
        layout(false);
        $store_id = (int)$_GET['store_id'];
        $price = (int)$_GET['price'];
        $order_number = $_GET['order_number'];
        $order_id = (int)$_GET['order_id'];
        $order = new \Home\Logic\OrderLogic();
        $data = $order->getOrder($order_number);
        if($store_id==$data['store_id'] && $price==$data['price'] && $data['id']==$order_id){
            //redirect('/pay/pay?store_id='.$data['store_id'].'&price='.$price.'&order_number='.$order_number);
        }else{
            return false;
        } 
    }

    /**
     * 个人中心
     */

    public function personal()
    {  
        layout('layout2');
        $items = $this->item->getItemsByStoreId($this->store_id,$status=1,true);
        foreach($items as $k=>$v){
            if($v['is_meal_set']==1){
                $meal_set_items = $this->item->getItemByMealSetId($v['id'], $this->store_id);
                $items[$k]['meal_set_items'] = $meal_set_items;   
            }
        }
        if($_SESSION['client_id']>0){
            $order = new \Home\Logic\OrderLogic();
            $count = $order->countOrders($this->store_id, $_SESSION['client_id']);
            $evaluate = new \Home\Logic\EvaluateLogic();
            $unread = $evaluate->unReadCount($this->store_id, $_SESSION['client_id']);
            $this->assign('unread',$unread);
            $this->assign('count',$count);
        }
        $this->assign('items',$items);
        $this->display( 'personal');
    }

    /*
     * 付款状态   
     */
    public function payStatus(){
        if($_SESSION['client_id']<1){
            redirect("/user/passport/login?store_id=".$this->store_id);
        }
        $status = (int)$_GET['status'];
        $order = new \Home\Logic\OrderLogic();
        $order_info = new \Home\Logic\OrderinfoLogic();
        $a = new \Home\Logic\ActionLogic();
        $item = new \Home\Logic\ShopitemLogic();
        $data = $order->getUserOrders(array_keys($this->stores), $_SESSION['client_id'], 0,$status);
        if(!$data){
            $data='目前没有相关订单哦！亲 (＾－＾)V';
        }else{
           $actions = array();
            foreach($data as $k=>$v){
                    $data[$k]['_items'] = $order_info->getOrderInfo($v['id'],$v['store_id']);
                    if($v['team_number']){
                        $i=0;
                        if (array_key_exists($v['action_id'], $actions)) {
                            $action = $actions[$v['action_id']];
                        } else {
                            $action = $a->getAction($v['action_id']);
                            $actions[$v['action_id']] = $action;
                        }
                        $orders['end_time'] = date('Y-m-d', $action['end_time']);
                        $orders['action_name'] = $action['action_name'];
                        $orders['action_price'] = json_decode($action['content'],true);
                        $team = $order->getTeam($v['team_number']);
                        if($action['model_type']==1){
                            $orders['my'] = $team[0]['user_id'] == $v['client_user'] ? '我开的团' : '我的参团';
                        }elseif($action['model_type']==3){
                            $orders['my'] = $team[0]['user_id'] == $v['client_user'] ? '我的公益' : '我的公益';
                        }
                           //作弊成团
                        if (time() - $v['create_time'] > 172800 && time() <= $v['end_time']) {
                            //先写死
                            $num = $order->getTeamNum($v['team_number']);
                            $orders['people_num'][$i] = (int) $num['num'] > 2 ? (int) $num['num'] : 3;
                            $orders['_status'] = '成团';
                        } else {
                            $num = $order->getTeamNum($v['team_number']);
                            $orders['people_num'] = (int) $num['num'];
                            if($action['model_type']==1){
                                $orders['_status'] = (int) $num['num'] > 2 ? '成团' : '未成团';
                            }elseif($action['model_type']==3){
                                $num = $order->getPayOrderCountByAid($action['id']);
                                $orders['people_num'] = (int) $num['count'];
                                //$orders['_status'] = (int) $num['num'] > 3 ? '众筹成功' : '众筹中';
                            }   
                        }
                        $data[$k]['_items']['orders'] = $orders;
                        $i++;    
                } 
            } 
        }
        
        $this->assign('status',$status);
        $this->assign('data',$data);
        if($status==0){
           $this->display('payStatus_0'); // 未付款
        }elseif($status==1){
            layout('layout2');
            $this->display('payStatus_1'); // 未完成
        }elseif($status==2){
            layout('layout2');
            $this->display('payStatus_2'); //已完成
        }elseif($status==4){
            layout('layout2');
            $this->display('payStatus_4'); //待评价
        }else{
            layout('layout2');
            $this->display('payStatus_3'); // 全部订单
        }


        
    }

    /**
     *  个人中心 收款状态 的分页内容追加
     */
    public function append(){
        if($_SESSION['client_id']<1){
            redirect("/user/passport/login?store_id=".$this->store_id);
        }
        $start = (int)$_GET['start'];
        $status = (int)$_GET['status'];
        $order = new \Home\Logic\OrderLogic();
        $order_info = new \Home\Logic\OrderinfoLogic();
        $a = new \Home\Logic\ActionLogic();
        $data = $order->getUserOrders(array_keys($this->stores), $_SESSION['client_id'], $start ,$status);
        $actions = array();
        foreach($data as $k=>$v){
          $data[$k]['_items'] = $order_info->getOrderInfo($v['id'],$v['store_id']);
            if($v['team_number']){
                $i=0;
                if (array_key_exists($v['action_id'], $actions)) {
                    $action = $actions[$v['action_id']];
                } else {
                    $action = $a->getAction($v['action_id']);
                    $actions[$v['action_id']] = $action;
                }
                $orders['end_time'] = date('Y-m-d', $action['end_time']);
                $orders['action_name'] = $action['action_name'];
                $orders['action_price'] = json_decode($action['content'],true);
                $team = $order->getTeam($v['team_number']);
                if($action['model_type']==1){
                    $orders['my'] = $team[0]['user_id'] == $v['client_user'] ? '我开的团' : '我的参团';
                }elseif($action['model_type']==3){
                    $orders['my'] = $team[0]['user_id'] == $v['client_user'] ? '我的公益' : '我的公益';
                }
                    //作弊成团
                    if (time() - $v['create_time'] > 172800 && time() <= $v['end_time']) {
                        //先写死
                        $num = $order->getTeamNum($v['team_number']);
                        $orders['people_num'][$i] = (int) $num['num'] > 2 ? (int) $num['num'] : 3;
                        $orders['_status'] = '成团';
                    } else {
                        $num = $order->getTeamNum($v['team_number']);
                        $orders['people_num'] = (int) $num['num'];
                        if($action['model_type']==1){
                            $orders['_status'] = (int) $num['num'] > 2 ? '成团' : '未成团';
                        }elseif($action['model_type']==3){
                            $num = $order->getPayOrderCountByAid($v['action_id']);
                            $orders['people_num'] = (int) $num['count'];
                            //$orders['_status'] = (int) $num['num'] > 3 ? '众筹成功' : '众筹中';
                        }   
                    }
                    $data[$k]['_items']['orders'] = $orders;
                    $i++;
            }
        }
        if(count( $data )>0){
            exit(json_encode( $data ));
        }
        exit('false');
    }




 
}
